package com.captjack.common.util.io.serializer;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;

import java.util.Arrays;

/**
 * <p>
 * ----------------------------------------------------------------------------- <br>
 * project name ：micro-service <br>
 * function：序列化 <br>
 * description：基于Protostuff的序列化、反序列化工具 <br>
 * copyright : © 2011-2018 <br>
 * ----------------------------------------------------------------------------- <br>
 * change history <br>
 * <table width="432" border="1">
 * <tr>
 * <td>version</td>
 * <td>time</td>
 * <td>author</td>
 * <td>change</td>
 * </tr>
 * <tr>
 * <td>1.0.0</td>
 * <td>2018/9/18 17:51</td>
 * <td>Jack Sparrow</td>
 * <td>create</td>
 * </tr>
 * </table>
 * <br>
 *
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 2018/9/18 17:51
 * package com.captjack.common.util.io.serializer
 */
public final class ProtostuffSerializerUtils {

    public static void main(String[] args) throws Exception {
        String s = "231";
        System.out.println(Arrays.toString(serializer(s)));
        System.out.println(deserializer(serializer(s), String.class));
    }

    private ProtostuffSerializerUtils() {

    }

    /**
     * 序列化
     *
     * @param t   实例
     * @param <T> 范型
     * @return byte数组
     */
    public static <T> byte[] serializer(T t) {
        return ProtostuffIOUtil.toByteArray(t, ProtostuffSchemaFactory.generateSchemaByClass(t.getClass()), LinkedBuffer.allocate(256));
    }

    /**
     * 反序列化
     *
     * @param bytes 序列化结果
     * @param clazz 类对象
     * @param <T>   范型
     * @return 反序列化对象
     * @throws Exception 异常
     */
    public static <T> T deserializer(byte[] bytes, Class<T> clazz) throws Exception {
        T t = clazz.getDeclaredConstructor().newInstance();
        ProtostuffIOUtil.mergeFrom(bytes, t, ProtostuffSchemaFactory.generateSchemaByClass(clazz));
        return t;
    }

}
